package conf

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"leaf/core/tool"
	"os"
	"path/filepath"
	"strings"
)

var (
	LenStackBuf = 4096
)

var Config = &config{}

type config struct {
	// log
	LogLevel   string
	LogPath    string
	LogFlag    int
	LogMaxSize int64
	LogHeader  string

	// server
	ServerId      int32
	ServerType    int32
	ServerTypeStr string

	// cluster
	RpcAddr    string
	RpcServers []string

	// connector
	WSAddr  string
	TCPAddr string

	// data base
	RedisAddr     string
	RedisChannels []string
	MongoAddr     string

	GoDebug bool
}

func Load(path string, tmap map[int32]string) {
	fileName := strings.TrimSuffix(filepath.Base(path), ".json")
	infos := strings.Split(fileName, "_")
	Config.ServerId = int32(tool.Atoi(infos[1]))
	Config.ServerType = Config.ServerId / 1000
	Config.ServerTypeStr = tmap[Config.ServerType]
	if Config.ServerTypeStr == "" {
		panic(fmt.Sprintf("LoadConfig ServerType = %d error", Config.ServerType))
	}
	Config.LogHeader = Config.ServerTypeStr
}

func LoadConfig(path string, tmap map[int32]string) {
	jsonFile, err := os.Open(path)
	if err != nil {
		panic(err)
	}
	defer jsonFile.Close()

	byteValue, err := ioutil.ReadAll(jsonFile)
	if err != nil {
		panic(err)
	}

	err = json.Unmarshal(byteValue, Config)
	if err != nil {
		panic(err)
	}

	Load(path, tmap)

	return
}
